import fs from 'then-fs'
async function fn() {
    const str = await fs.readFile('./txt/data.json')
    return JSON.parse(str)
}
// fn().then(res => {
//     console.log(res);
// })
async function addGet(obj) {
    try {
        const arr = await fn()
        obj.id = arr[arr.length - 1].id + 1
        arr.push(obj)
        fs.writeFile('./txt/data.json', JSON.stringify(arr))
        return'添加成功'
    } catch(e) {
        return '添加失败'
    }
}
// addGet(
//     {
//         "author": "程鹏飞",
//         "bookname": "三体1",
//         "publisher": "武汉人民出版社"
//     }
// ).then(res => {
//     console.log(res);
// })
async function delData(id) {
    try {
        const arr = await fn()
    const newArr = arr.filter(ele => id != ele.id)
    fs.writeFile('./txt/data.json', JSON.stringify(newArr))
    return '删除成功'
    } catch (e) {
        return '删除失败'
    } 
}
// delData(3).then(res => {
//     console.log(res);
// })
async function upData(obj) {
    try {
        const arr = await fn()
    const index = arr.findIndex(ele => ele.id == obj.id)
    arr.splice(index,1 ,obj)
    fs.writeFile('./txt/data.json', JSON.stringify(arr))
    return '修改成功'
    } catch (e) {
        return '修改失败'
    }
}
upData({
    "author":"聪明蛋儿","bookname":"三位一体","publisher":"家君出版社","id":3
}).then(res => {
    console.log(res);
})